package rexsee.core.widget;

import rexsee.core.browser.Browser;
import rexsee.core.style.StyleSheet;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Build.VERSION;
import android.os.Handler;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.view.Window;
import android.view.WindowManager;

public class DivDialog extends Dialog {

	protected final Browser mBrowser;
	protected final Context mContext;
	public final StyleSheet styleSheet;
	public final Div div;
	private final DialogInterface mDialog;
	private final String mDialogId;
	private final Handler mHandler = new Handler();

	//for Moving
	private final float maxOffset = 10;
	private float originalX;
	private float originalY;
	private float x;
	private float y;

	private boolean syncTag = false;

	public DivDialog(final Browser browser, String dialogId, String style) {

		super(browser.getContext(), android.R.style.Theme_Panel);
		mBrowser = browser;
		mContext = browser.getContext();
		mDialog = this;
		mDialogId = dialogId;
		styleSheet = (new StyleSheet(mContext)).parseStyle(style);

		div = new Div(mContext);
		div.styleSheet = styleSheet;
		div.setDivStyle();
		div.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
		int windowStyle = styleSheet.getWindowStyle();
		if (windowStyle != 0) div.setBackgroundResource(windowStyle);
		if (styleSheet.window_moveable.equalsIgnoreCase("true")) {
			div.setClickable(true);
			div.setOnTouchListener(new View.OnTouchListener() {
				@Override
				public boolean onTouch(View v, MotionEvent event) {
					int a = event.getAction();
					if (a == MotionEvent.ACTION_DOWN) {
						x = event.getRawX();
						y = event.getRawY();
						originalX = x;
						originalY = y;
					} else if (a == MotionEvent.ACTION_MOVE) {
						Window window = getWindow();
						WindowManager.LayoutParams attr = window.getAttributes();
						attr.x = (int) (attr.x + event.getRawX() - x);
						attr.y = (int) (attr.y + event.getRawY() - y);
						window.setAttributes(attr);
						x = event.getRawX();
						y = event.getRawY();
					} else if (a == MotionEvent.ACTION_UP || a == MotionEvent.ACTION_CANCEL) {
						if (Math.abs(originalX - event.getRawX()) < maxOffset && Math.abs(originalY - event.getRawY()) < maxOffset) {
							onClick(mDialog);
						}
					}
					return false;
				}
			});
		} else {
			div.setClickable(false);
		}

		final int autoHide = Integer.parseInt(styleSheet.window_auto_hide);
		if (autoHide > 0) {
			mHandler.postDelayed(new Runnable() {
				@Override
				public void run() {
					DivDialog.this.dismiss();
				}
			}, autoHide * 1000);
		}

		Window window = this.getWindow();
		window.requestFeature(Window.FEATURE_NO_TITLE);
		window.setFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND, WindowManager.LayoutParams.FLAG_DIM_BEHIND);
		if (styleSheet.window_fullscreen.equalsIgnoreCase("fullscreen")) window.setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
		if (styleSheet.window_modeless.equals("true")) window.setFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL, WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL);
		if (styleSheet.window_blur_behind.equalsIgnoreCase("true")) window.setFlags(WindowManager.LayoutParams.FLAG_BLUR_BEHIND, WindowManager.LayoutParams.FLAG_BLUR_BEHIND);
		if (Integer.parseInt(VERSION.SDK) >= 5) {
			//WindowManager.LayoutParams.FLAG_SHOW_WALLPAPER, for SDK 5+;
			int FLAG_SHOW_WALLPAPER = 1048576;
			if (styleSheet.window_show_wallpaper.equalsIgnoreCase("true")) window.setFlags(FLAG_SHOW_WALLPAPER, FLAG_SHOW_WALLPAPER);
		} else {
			// No effect for window_show_wallpaper, for SDK 5-
		}

		this.setCancelable(styleSheet.window_cancelable.equalsIgnoreCase("true"));
		this.setCanceledOnTouchOutside(styleSheet.window_outside_cancelable.equalsIgnoreCase("true"));

		this.setContentView(div);

	}
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			if (mBrowser.menu.isOptionsMenuOpen) {
				((Activity) mContext).closeOptionsMenu();
				return true;
			} else if (styleSheet.window_cancelable.equalsIgnoreCase("true")) {
				dismiss();
				return true;
			}
		} else if (keyCode == KeyEvent.KEYCODE_MENU) {
			((Activity) mContext).openOptionsMenu();
		} else if (keyCode == KeyEvent.KEYCODE_SEARCH) {
			return true;
		} else if (keyCode == KeyEvent.KEYCODE_FOCUS) {
		} else if (keyCode == KeyEvent.KEYCODE_VOLUME_UP) {
		} else if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN) {
		} else {
		}
		return false;
	}

	public String getDialogId() {
		return mDialogId;
	}
	public void addChild(View child) {
		child.setClickable((styleSheet.window_moveable.equalsIgnoreCase("true")) ? false : true);
		div.addChild(child);
	}
	public void start() {
		startDivDialog();
	}
	protected void startDivDialog() {

		try {
			show();

			Window window = getWindow();
			WindowManager.LayoutParams attr = window.getAttributes();

			attr.type = (styleSheet.window_split_screen.equalsIgnoreCase("true")) ? WindowManager.LayoutParams.TYPE_INPUT_METHOD : WindowManager.LayoutParams.TYPE_APPLICATION;
			attr.windowAnimations = styleSheet.getWindowAnimation();
			attr.alpha = styleSheet.getAlpha();
			attr.dimAmount = Float.parseFloat(styleSheet.window_dim_amount);

			attr.gravity = styleSheet.getWindowGravity();

			int top = styleSheet.getTop();
			if (top < 0) {
				top = mBrowser.application.screenHeight + top;
			}
			int left = styleSheet.getLeft();
			if (left < 0) {
				left = mBrowser.application.screenWidth + left;
			}
			if (left != 0) attr.x = left;
			if (top != 0) attr.y = top;

			attr.width = styleSheet.getWidth();
			attr.height = styleSheet.getHeight();

			window.setAttributes(attr);

			if (styleSheet.visibility.equalsIgnoreCase("hidden") || styleSheet.visibility.equalsIgnoreCase("gone")) {
				hide();
			}

		} catch (Exception e) {
			mBrowser.exception(this.getClass().getName(), e);
		}

	}

	public void removeChilds() {
		div.removeChilds();
	}

	public void setStyle(final String style) {

		syncTag = false;
		((Activity) mContext).runOnUiThread(new Runnable() {
			@Override
			public void run() {

				try {

					styleSheet.parseStyle(style);
					div.setDivStyleWithoutLayoutParams();

					Window window = DivDialog.this.getWindow();
					WindowManager.LayoutParams attr = window.getAttributes();
					attr.alpha = styleSheet.getAlpha();
					attr.dimAmount = Float.parseFloat(styleSheet.window_dim_amount);
					attr.gravity = styleSheet.getWindowGravity();
					int top = styleSheet.getTop();
					if (top < 0) {
						top = mBrowser.application.screenHeight + top;
					}
					int left = styleSheet.getLeft();
					if (left < 0) {
						left = mBrowser.application.screenWidth + left;
					}
					if (left != 0) attr.x = left;
					if (top != 0) attr.y = top;
					attr.width = styleSheet.getWidth();
					attr.height = styleSheet.getHeight();
					window.setAttributes(attr);

					DivDialog.this.setCancelable(styleSheet.window_cancelable.equalsIgnoreCase("true"));
					DivDialog.this.setCanceledOnTouchOutside(styleSheet.window_outside_cancelable.equalsIgnoreCase("true"));

					if (styleSheet.visibility.equalsIgnoreCase("hidden") || styleSheet.visibility.equalsIgnoreCase("gone")) {
						DivDialog.this.hide();
					} else {
						DivDialog.this.show();
					}

				} catch (Exception e) {
					mBrowser.exception("Div", e);
				}

				syncTag = true;
			}
		});

		while (!syncTag) {
			try {
				Thread.sleep(20);
			} catch (Exception e) {

			}
		}
		return;

	}
	public String getStyle(String name) {
		return styleSheet.getStyle(name);
	}

	protected void onClick(DialogInterface dialog) {
	}

}
